const fs = require('fs-extra'),
    path = require('path'),
    swc = require('@swc/core'),
    
    getOpts = (path,opts,jest) => {
        jest = jest || false;
        opts = opts || {};

        let defaultOptions = {
            target:'es2018',                    // 目录版本 "es2016"、"es3"、"es5"、"es2015"、"es2017"、"es2018"、"es2019"
            module:'es6',                       // 导出规范 "es6"、"commonjs"、"umd"、"amd"
            jsx:path.endsWith('.tsx'),  
            experimentalDecorators:true,        // 装饰器启用开关
            emitDecoratorMetadata:true,         // 装饰器元数据启用支持
            dynamicImport:true,                 // import 表达式支持
            esModuleInterop:true,               // 是否支持以 import 引用 commonjs 包
            react:undefined,
            keepClassNames:undefined,           // 类名保留
            sourcemap:false                     // 调试信息
        };
        for(let key in opts){
            defaultOptions[key] = opts[key];
        };
        opts = defaultOptions;

        return {
            filename: path,
            jsc: {
                target: opts.target,
                parser: {
                    syntax: 'typescript',
                    tsx: opts.jsx,
                    decorators: opts.experimentalDecorators,
                    dynamicImport: opts.dynamicImport,
                },
                transform: {
                    legacyDecorator: opts.experimentalDecorators,
                    decoratorMetadata: opts.emitDecoratorMetadata,
                    react: opts.react,
                    hidden: {
                        jest,
                    },
                },
                keepClassNames: opts.keepClassNames,
            },
            minify: false,
            isModule: true,
            module: {
                type: opts.module,
                noInterop: !opts.esModuleInterop,
            },
            sourceMaps: opts.sourcemap,
            swcrc: false,
        }
    };

/**
 * 编译单个文件 Ts 文件
 * @param {string} srcPath ts文件路径
 * @param {string} outPath 文件输出路径
 */
const buildFile = (srcPath,outPath,module,sourcemap)=>{
    let source = fs.readFileSync(srcPath,'utf-8'),
        options = getOpts(srcPath,{module:module,sourcemap:sourcemap});
    
    // transformJest:swc.transform(source,getOpts(srcPath,{module:module,sourcemap:sourcemap}),true)
    // transform:swc.transform(source,getOpts(srcPath,{module:module,sourcemap:sourcemap}))
    // transformSync:swc.transformSync(source,getOpts(srcPath,{module:module,sourcemap:sourcemap}))

    swc.transform(source,options).then(v => {
        let dirPath = path.dirname(outPath);
        fs.ensureDirSync(dirPath);
        fs.writeFileSync(outPath,v.code);
        console.log("文件编译成功：",srcPath,"->",outPath);
    }).catch(e => {
        throw e;
    });
};

module.exports = buildFile;